package com.hn.zhijian.system.rsasdk;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * RSA加解密工具类
 * 
 * @author shaohai.Liu
 * @date 2017-8-7
 * @version 0.0.1-SNAPSHOT
 */
public class RSA extends AbstractSecurity {
	/**
	 * 字节数据转字符串专用集合
	 */
	final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	/**
	 * 加解密算法/模式/填充方式
	 */
	final String algorithmStr = "RSA/ECB/PKCS1Padding";

	/**
	 * 从字符串中加载公钥
	 * 
	 * @param publicKeyStr
	 *            公钥数据字符串
	 * @throws SecurityException
	 *             加载公钥时产生的异常
	 */
	public RSAPublicKey loadPublicKeyByStr(String publicKeyStr) throws SecurityException {
		try {
			byte[] buffer = decode(publicKeyStr);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
			return (RSAPublicKey) keyFactory.generatePublic(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new SecurityException(e);
		} catch (InvalidKeySpecException e) {
			throw new SecurityException(e);
		} catch (NullPointerException e) {
			throw new SecurityException(e);
		}
	}

	/**
	 * 从字符串中加载私钥
	 * 
	 * @param privateKeyStr
	 *            私钥字符串
	 * @return 私钥对象
	 * @throws SecurityException
	 *             加解密异常
	 */
	public RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr) throws SecurityException {
		try {
			byte[] buffer = decode(privateKeyStr);
			PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new SecurityException(e);
		} catch (InvalidKeySpecException e) {
			throw new SecurityException(e);
		} catch (NullPointerException e) {
			throw new SecurityException(e);
		}
	}

	/**
	 * 公钥加密过程
	 * 
	 * @param publicKey
	 *            公钥
	 * @param plainTextData
	 *            明文数据
	 * @return 密文串
	 * @throws SecurityException
	 *             加密过程中的异常信息
	 */
	public byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws SecurityException {
		if (publicKey == null) {
			throw new SecurityException("公钥不存在。");
		}

		Cipher cipher = null;

		try {
			// 使用默认RSA
			cipher = Cipher.getInstance(algorithmStr);
			// cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);

			byte[] output = cipher.doFinal(plainTextData);
			return output;
		} catch (NoSuchAlgorithmException e) {
			throw new SecurityException(e);
		} catch (NoSuchPaddingException e) {
			throw new SecurityException(e);
		} catch (InvalidKeyException e) {
			throw new SecurityException(e);
		} catch (IllegalBlockSizeException e) {
			throw new SecurityException(e);
		} catch (BadPaddingException e) {
			throw new SecurityException(e);
		}
	}

	/**
	 * 私钥加密过程
	 * 
	 * @param privateKey
	 *            私钥
	 * @param plainTextData
	 *            明文数据
	 * @return 密文串
	 * @throws SecurityException
	 *             加密过程中的异常信息
	 */
	public byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData) throws SecurityException {
		if (privateKey == null) {
			throw new SecurityException("私钥不存在。");
		}

		Cipher cipher = null;

		try {
			// 使用默认RSA
			cipher = Cipher.getInstance(algorithmStr);
			cipher.init(Cipher.ENCRYPT_MODE, privateKey);
			byte[] output = cipher.doFinal(plainTextData);
			return output;
		} catch (NoSuchAlgorithmException e) {
			throw new SecurityException(e);
		} catch (NoSuchPaddingException e) {
			throw new SecurityException(e);
		} catch (InvalidKeyException e) {
			throw new SecurityException(e);
		} catch (IllegalBlockSizeException e) {
			throw new SecurityException(e);
		} catch (BadPaddingException e) {
			throw new SecurityException(e);
		}
	}

	/**
	 * 私钥解密过程
	 * 
	 * @param privateKey
	 *            私钥
	 * @param cipherData
	 *            密文数据
	 * @return 明文
	 * @throws SecurityException
	 *             解密过程中的异常信息
	 */
	public byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws SecurityException {
		if (privateKey == null) {
			throw new SecurityException("私钥不存在。");
		}

		Cipher cipher = null;
		try {
			// 使用默认RSA
			cipher = Cipher.getInstance(algorithmStr);
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
			byte[] output = cipher.doFinal(cipherData);
			return output;
		} catch (NoSuchAlgorithmException e) {
			throw new SecurityException(e);
		} catch (NoSuchPaddingException e) {
			throw new SecurityException(e);
		} catch (InvalidKeyException e) {
			throw new SecurityException(e);
		} catch (IllegalBlockSizeException e) {
			throw new SecurityException(e);
		} catch (BadPaddingException e) {
			throw new SecurityException(e);
		}
	}

	/**
	 * 公钥解密过程
	 * 
	 * @param publicKey
	 *            公钥
	 * @param cipherData
	 *            密文数据
	 * @return 明文
	 * @throws SecurityException
	 *             解密过程中的异常信息
	 */
	public byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData) throws SecurityException {
		if (publicKey == null) {
			throw new SecurityException("私钥不存在。");
		}
		Cipher cipher = null;
		try {
			// 使用默认RSA
			cipher = Cipher.getInstance(algorithmStr);
			cipher.init(Cipher.DECRYPT_MODE, publicKey);
			byte[] output = cipher.doFinal(cipherData);
			return output;
		} catch (NoSuchAlgorithmException e) {
			throw new SecurityException(e);
		} catch (NoSuchPaddingException e) {
			throw new SecurityException(e);
		} catch (InvalidKeyException e) {
			throw new SecurityException(e);
		} catch (IllegalBlockSizeException e) {
			throw new SecurityException(e);
		} catch (BadPaddingException e) {
			throw new SecurityException(e);
		}
	}

	/**
	 * 字节数据转十六进制字符串
	 * 
	 * @param data
	 *            输入数据
	 * @return 十六进制内容
	 */
	public String byteArrayToString(byte[] data) {
		StringBuilder stringBuilder = new StringBuilder();

		for (int i = 0; i < data.length; i++) {
			// 取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移
			stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);
			// 取出字节的低四位 作为索引得到相应的十六进制标识符
			stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
			if (i < data.length - 1) {
				stringBuilder.append(' ');
			}
		}

		return stringBuilder.toString();
	}
}
